import { defineStore } from 'pinia'

export interface TabItem {
  title: string
  path: string
}

export const useTabsStore = defineStore('tabs', {
  state: () => ({
    tabs: [] as TabItem[],
    activeTab: '',
    defaultTab: {} as TabItem,
  }),
  actions: {
    addTab(route: TabItem) {
      if (!route.path) return
      const existing = this.tabs.find((t) => t.path === route.path)
      if (!existing) {
        this.tabs.push({
          title: route.title,
          path: route.path,
        })
      }
      this.activeTab = route.path
    },

    removeTab(targetName: string) {
      const tabs = this.tabs
      let activeName = this.activeTab

      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.path === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1]
            activeName = nextTab?.path || ''
          }
        })
      }

      this.tabs = tabs.filter((tab) => tab.path !== targetName)

      // console.log(this.tabs)
      if (this.tabs.length === 0) {
        this.tabs = [this.defaultTab]
        activeName = this.defaultTab.path
      }

      this.activeTab = activeName
      return activeName
    },

    initDefultTab(route: TabItem) {
      this.defaultTab = Object.assign({}, route)
    },

    persistentTabs() {
      sessionStorage.setItem('tabList', JSON.stringify(this.tabs))
    },
    restoreTabs() {
      const tabList = sessionStorage.getItem('tabList') // 获取sessionStorage中的tab路径
      if (tabList) { // 如果存在tab路径
        const oldTabs = JSON.parse(tabList) // 将tab路径转换为数组
        if (oldTabs.length > 0) { // 如果数组长度大于0
          this.tabs = oldTabs // 将数组赋值给tabsStore.tabs
        }
      }
    },

    initTabs(){
      sessionStorage.removeItem('tabList') // 清除sessionStorage中的tab路径
      this.tabs = []
      this.activeTab = ''
      this.defaultTab = {} as TabItem
    }
  },
})
